const dao = require('./dao');
const pool = dao.pool; // 确认你的dao模块里导出连接池对象 pool
const query = dao.query_game;

exports.getRTP = async (data) => {
    let sql = `select * from rtp where gameId = ?`;
    const gameId = data;
    try {
        const ret = await query(sql, [gameId]);
        return {
            respCode: "SUCCESS",
            data: ret[0]
        };
    } catch (err) {
        console.log('获取RTP信息失败:', err);
        return { respCode: "FAIL", message: err.message };
    }
}

exports.updateRTP = async (gameId, total_bet, total_win, rtp) => {
    let sql = `update rtp set total_bet = ?, total_win = ?, rtp = ? where gameId = ?`;
    try {
        const ret = await query(sql, [total_bet, total_win, rtp, gameId]);
        return {
            respCode: "SUCCESS",
            data: ret
        };
    } catch (err) {
        console.log('更新RTP信息失败:', err);
        return { respCode: "FAIL", message: err.message };
    }
}

exports.getUserCoin = async (playerId) => {
    let sql = `select coin from players where playerId = ?`;
    try {
        const ret = await query(sql, [playerId]);
        return {
            respCode: "SUCCESS",
            data: ret[0]
        };
    } catch (err) {
        console.log('获取用户余额失败:', err);
        return { respCode: "FAIL", message: err.message };
    }
}

exports.updatePlayerCoin = async (playerId, win, bet) => {
    try {
        const playerRes = await query('SELECT coin FROM players WHERE playerId = ?', [playerId]);
        if (playerRes.length === 0) {
            return {
                respCode: "FAIL",
                message: "玩家不存在"
            };
        }

        const currentCoin = playerRes[0].coin;

        if (currentCoin < bet) {
            return {
                respCode: "FAIL",
                message: "金币不足，无法结算",
                coin: currentCoin
            };
        }

        const sql = `UPDATE players SET coin = coin + ? WHERE playerId = ?`;
        const ret = await query(sql, [win, playerId]);

        return {
            respCode: "SUCCESS",
            data: ret,
            coin: currentCoin + win
        };
    } catch (err) {
        console.log('更新用户余额失败:', err);
        return {
            respCode: "ERROR",
            message: err.message
        };
    }
};

exports.getRecharge = async (playerId) => {
    let sql = `select * from betjihe where playerId = ?`;
    try {
        const ret = await query(sql, [playerId]);
        return {
            respCode: "SUCCESS",
            data: ret
        };
    } catch (err) {
        console.log('获取充值记录失败:', err);
        return { respCode: "FAIL", message: err.message };
    }
}

exports.updatePlayerRecharge = async (recharge) => {
    for (let i = 0; i < recharge.length; i++) {
        const element = recharge[i];
        const { id, success, jindu } = element;
        const sql = `UPDATE betjihe SET success = ?, jindu = ? WHERE id = ?`;
        try {
            await query(sql, [success, jindu, id]);
        } catch (err) {
            console.error(`更新充值记录失败，index=${i}, 数据=${JSON.stringify(element)}，错误信息：`, err);
        }
    }
};

exports.getGameLevel = async (gameId) => {
    let sql = `select level from game where gameId = ?`;
    try {
        const ret = await query(sql, [gameId]);
        return {
            success: true,
            data: ret[0]
        };
    } catch (err) {
        console.log('获取游戏难度失败:', err);
        return { success: false, message: err.message };
    }
};

exports.insertBetData = async (bet, winscore, win, gameId, gameName, gamType, playerId) => {
    let sql = `insert into betHistory(playerId,gameId,gameName,gameType,bet, winscore, win,betTime,betOrderId) values(?,?,?,?,?,?,?,?,?)`;
    try {
        const timestamp = Date.now();
        const random = Math.floor(1000 + Math.random() * 9000);
        let orderId = `BETORD${timestamp}${random}`;

        const result = await query(sql, [playerId, gameId, gameName, gamType, bet, winscore, win, new Date(), orderId]);

        // 如果需要删旧记录，代码可解开注释
        /*
        const deleteSql = `
            DELETE FROM betHistory
            WHERE playerId = ?
              AND id NOT IN (
                SELECT id FROM (
                    SELECT id FROM betHistory
                    WHERE playerId = ?
                    ORDER BY betTime DESC
                    LIMIT 1000
                ) AS temp
              )
        `;
        await query(deleteSql, [playerId, playerId]);
        */

        return {
            success: true,
            message: result.affectedRows
        };
    } catch (err) {
        console.log('插入游戏数据失败:', err);
        return { success: false, message: err.message };
    }
};

// --------------------- 查询玩家的总下注和总赢分 ---------------------

exports.getPlayerTotalData = async (playerId, isFree) => {
    let sql = `select total_bet, total_win, coin from players where playerId = ?`;
    if (isFree) {
        sql = `select total_bet_free, total_win_free, coin from players where playerId = ?`;
    }
    try {
        const ret = await query(sql, [playerId]);
        return {
            respCode: "SUCCESS",
            data: ret[0]
        };
    } catch (err) {
        console.log('获取玩家总下注和总赢分失败:', err);
    }
};
// --------------------- 查询玩家打的是免费还是充值的 ---------------------
exports.getPlayerFreeOrPay = async (playerId) => {
    let sql = `
        SELECT * 
        FROM betjihe 
        WHERE playerId = ? AND success = 0
        ORDER BY time ASC
    `;

    try {
        const ret = await query(sql, [playerId]);

        // 计算所有记录中 target - jindu 的累加结果
        let totalDifference = ret.reduce((sum, row) => {
            return sum + (row.target - row.jindu);
        }, 0);

        // 返回数据，包括单个记录和差值总和
        return {
            respCode: "SUCCESS",
            data: {
                totalDifference,
                record: ret[0] || null  // 返回第一个记录，如果没有符合条件的记录，返回 null
            }
        };
    } catch (err) {
        console.log('查询玩家投注数据失败:', err);
        return {
            respCode: "ERROR",
            message: "查询失败"
        };
    }
};

// --------------------- 事务示例：更新玩家金币和投注记录 ---------------------
exports.updatePlayerCoinAndBetRecord = async (playerId, win, bet, winscore, isFree) => {
    const connection = await pool.getConnection();
    try {
        await connection.beginTransaction();

        const [playerRes] = await connection.query('SELECT coin FROM players WHERE playerId = ?', [playerId]);
        if (playerRes.length === 0) {
            await connection.rollback();
            return { respCode: "FAIL", message: "玩家不存在" };
        }

        const currentCoin = playerRes[0].coin;
        if (currentCoin < bet) {
            await connection.rollback();
            return { respCode: "FAIL", message: "金币不足，无法结算", coin: currentCoin };
        }


        let updateSql = `UPDATE players SET coin = coin + ?, total_bet = total_bet + ?, total_win = total_win + ? WHERE playerId = ?`;
        if (isFree) {
            updateSql = `UPDATE players SET coin = coin + ?, total_bet_free = total_bet_free + ?, total_win_free = total_win_free + ? WHERE playerId = ?`;
        }
        // 更新玩家金币
        const [ret] = await connection.query(
            updateSql,
            [win, bet, winscore, playerId]
        );

        // 更新充值进度
        const [rows] = await connection.query(
            `SELECT * FROM betjihe WHERE playerId = ? AND success = 0 ORDER BY time ASC`, [playerId]
        );

        let remainingBet = bet;
        for (const row of rows) {
            if (remainingBet <= 0) break;

            let newJindu = row.jindu + remainingBet;
            let success = 0;
            if (newJindu >= row.target) {
                remainingBet = newJindu - row.target;
                newJindu = row.target;
                success = 1;
            } else {
                remainingBet = 0;
            }

            await connection.query(
                `UPDATE betjihe SET jindu = ?, success = ? WHERE id = ?`,
                [newJindu, success, row.id]
            );
        }

        await connection.commit();
        return { respCode: "SUCCESS", data: ret, coin: currentCoin + win };
    } catch (err) {
        await connection.rollback();
        console.error('事务失败:', err);
        return { respCode: "ERROR", message: err.message };
    } finally {
        connection.release();
    }
};


// --------------------- 获取玩家的免费转盘次数 ---------------------
exports.getFreeSpinTimes = async (playerId, gameId) => {
    try {
        const sql = 'SELECT free_times, bet, bet_level FROM free_spin WHERE playerId = ? AND game_id = ?';
        const ret = await query(sql, [playerId, gameId]);
        if (ret.length > 0) {
            return ret[0];
        } else {
            return 0;
        }
    } catch (error) {
        console.log('获取免费旋转次数失败:', error);
        return 0;
    }
};

// --------------------- 修改玩家的免费转盘次数 ---------------------
exports.updateFreeSpinTimes = async (playerId, gameId, freeTimes, bet, betLevel) => {
    try {
        let sql = `
            INSERT INTO free_spin (playerId, game_id, free_times${bet !== undefined && betLevel !== undefined ? ', bet, bet_level' : ''})
            VALUES (? , ?, ?${bet !== undefined && betLevel !== undefined ? ', ?, ?' : ''})
            ON DUPLICATE KEY UPDATE free_times = VALUES(free_times)
            ${bet !== undefined && betLevel !== undefined ? ', bet = VALUES(bet), bet_level = VALUES(bet_level)' : ''}
        `;

        let params = [playerId, gameId, freeTimes];
        if (bet !== undefined && betLevel !== undefined) {
            params.push(bet, betLevel);
        }

        await query(sql, params);
    } catch (error) {
        console.log('修改/插入玩家免费转盘次数失败:', error);
    }
};

// --------------------- 获取玩家的免费转盘信息 ---------------------
exports.getFreeSpinData = async (playerId, gameId) => {
    try {
        const sql = `
        SELECT * FROM free_spin WHERE playerId = ? AND game_id = ?
        `;

        const ret = await query(sql, [playerId, gameId]);
        return {
            respCode: "SUCCESS",
            data: ret[0]
        }
    } catch (error) {
        console.log('获取玩家免费转盘信息失败:', error);
        return {
            respCode: "FAIL",
            message: error
        };
    }
};